//
//  ShareViaWeiboController.m
//  PrivateTaxCalculator
//
//  Created by albert ma on 1/7/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ShareViaWeiboController.h"

//#define kOAuthConsumerKey				@"4101553713"		//REPLACE ME
//#define kOAuthConsumerSecret			@"4c330b2a95e0451aca6a76bfbfbf01bf"		//REPLACE ME
#define kOAuthConsumerKey				@"3983859935"		//REPLACE ME
#define kOAuthConsumerSecret			@"201fea7b1e1203a76a10f3be570f5abb"		//REPLACE ME
@interface ShareViaWeiboController (Private)

- (void)removeCachedOAuthDataForUsername:(NSString *) username;

@end

@implementation ShareViaWeiboController
@synthesize shareContentTextView, sharedContent;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [draft release];
        draft = [[Draft alloc]initWithType:DraftTypeNewTweet];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    UIImage* paper = [UIImage imageNamed:@"paper_material"];
    self.view.backgroundColor = [UIColor colorWithPatternImage:paper];
    [self.shareContentTextView setText:sharedContent];
    if (!_engine){
		_engine = [[OAuthEngine alloc] initOAuthWithDelegate: self];
		_engine.consumerKey = kOAuthConsumerKey;
		_engine.consumerSecret = kOAuthConsumerSecret;
	}

}

- (void)viewDidUnload
{
    [self setShareContentTextView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)gotoBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)shareSinaWeibo:(id)sender {
    
    NSString* inputContent = [shareContentTextView text];
    if(inputContent == nil || [inputContent length] == 0)
    {
        UIAlertView *serviceDisableAlert =[[UIAlertView alloc]initWithTitle:@"提示" message:@"无内容" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [serviceDisableAlert show];
        [serviceDisableAlert release];
        return;
    }
    [self removeCachedOAuthDataForUsername:_engine.username];
	[_engine signOut];
    
    /*avoid from revealing other user to send weibo's content*/
	UIViewController *controller = [OAuthController controllerToEnterCredentialsWithEngine: _engine delegate: self];
	
	if (controller) 
		[self presentModalViewController: controller animated: YES];

    
   }

//- (void)loadData {
//	if (weiboClient) { 
//		[weiboClient release];
//	}
//	weiboClient = [[WeiboClient alloc] initWithTarget:self 
//											   engine:_engine
//											   action:@selector(timelineDidReceive:obj:)];
//	[weiboClient getFollowedTimelineSinceID:0 
//							 startingAtPage:0 count:100];
//}

//- (void)loadTimeline {
//	UIViewController *controller = [OAuthController controllerToEnterCredentialsWithEngine: _engine delegate: self];
//	
//	if (controller) 
//		[self presentModalViewController: controller animated: YES];
//	else {
//		NSLog(@"Authenicated for %@..", _engine.username);
//		[OAuthEngine setCurrentOAuthEngine:_engine];
//		[self loadData];
//		
//	}
//}

- (IBAction)touchScreen:(id)sender {
    [shareContentTextView resignFirstResponder];
}
- (void)dealloc {
    [shareContentTextView release];
    [content release];
    [draft release];
    [_engine release];
    [super dealloc];
}

//=============================================================================================================================
#pragma mark OAuthEngineDelegate
- (void) storeCachedOAuthData: (NSString *) data forUsername: (NSString *) username {
	NSUserDefaults			*defaults = [NSUserDefaults standardUserDefaults];
	
	[defaults setObject: data forKey: @"authData"];
	[defaults synchronize];
}

- (NSString *) cachedOAuthDataForUsername: (NSString *) username {
	return [[NSUserDefaults standardUserDefaults] objectForKey: @"authData"];
}

- (void)removeCachedOAuthDataForUsername:(NSString *) username{
	NSUserDefaults			*defaults = [NSUserDefaults standardUserDefaults];
	
	[defaults removeObjectForKey: @"authData"];
	[defaults synchronize];
}

- (IBAction)cancel:(id)sender {
	
	[self dismissModalViewControllerAnimated:YES];
}
//=============================================================================================================================
#pragma mark OAuthSinaWeiboControllerDelegate
- (void) OAuthController: (OAuthController *) controller authenticatedWithUsername: (NSString *) username {
	NSLog(@"Authenicated for %@", username);
    if([shareContentTextView.text length] > 140)
    {
        draft.text = [shareContentTextView.text substringToIndex: 140];
    }
    else
    {
        draft.text = shareContentTextView.text;
    }
    
    NSLog(@"OAuthEngine currentOAuthEngine consumerkey: %@", _engine.consumerKey);
    if(weiboClient)
    {
        [weiboClient release];
    }
    weiboClient = [[WeiboClient alloc] initWithTarget:self 
                                                 engine:_engine
                                                 action:@selector(postStatusDidSucceed:obj:)];
//    WeiboClient *client = [[WeiboClient alloc] initWithTarget:self 
//													   engine:_engine
//													   action:@selector(postStatusDidSucceed:obj:)];
	weiboClient.context = [draft retain];
	draft.draftStatus = DraftStatusSending;
	if (draft.attachmentImage) {
		[weiboClient upload:draft.attachmentData status:draft.text];
	}
	else {
        [weiboClient post:draft.text];
	}
        
}

- (void) OAuthControllerFailed: (OAuthController *) controller {
	NSLog(@"Authentication Failed!");
	//UIViewController *controller = [OAuthController controllerToEnterCredentialsWithEngine: _engine delegate: self];
	if (controller) 
		[self presentModalViewController: controller animated: YES];
    draft.text = shareContentTextView.text;
	
	
}

- (void) OAuthControllerCanceled: (OAuthController *) controller {
	NSLog(@"Authentication Canceled.");
	//UIViewController *controller = [OAuthController controllerToEnterCredentialsWithEngine: _engine delegate: self];
	
//	if (controller) 
//        [self presentModalViewController: controller animated: YES];
	
}

- (void)postStatusDidSucceed:(WeiboClient*)sender obj:(NSObject*)obj;
{
	Draft *sentDraft = nil;
	if (sender.context && [sender.context isKindOfClass:[Draft class]]) {
		sentDraft = (Draft *)sender.context;
       
	}
	
    if (sender.hasError) {
        [sender alert];
        
        return;
    }
   
    NSDictionary *dic = nil;
    if (obj && [obj isKindOfClass:[NSDictionary class]]) {
        dic = (NSDictionary*)obj;    
    }
	
    if (dic) {
        Status* sts = [Status statusWithJsonDictionary:dic];
		if (sts) {
			//delete draft!
			if (sentDraft) {
				
			}
		}
    }
    UIAlertView *serviceDisableAlert =[[UIAlertView alloc]initWithTitle:@"成功" message:@"发送微博成功！" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [serviceDisableAlert show];
    [serviceDisableAlert release];
   	[self cancel:nil];
}


@end
